package oj;

public class Num606 {
    StringBuilder sb=new StringBuilder();
    public String tree2str(TreeNode root) {
        if(root==null){
            return "";
        }
        return preOrder(root);
    }
    private String preOrder(TreeNode root) {
        if (root == null) {
            return "";
        }
        sb.append(root.val);
        if (root.left != null) {
            sb.append("(");
            //先序遍历左树
            preOrder(root.left);
            sb.append(")");
        } else {
            //左空右不空
            if (root.right != null) {
                sb.append("()");
            }
        }
        if (root.right != null) {
            sb.append("(");
            //先序遍历右树
            preOrder(root.right);
            sb.append(")");
        }
        return sb.toString();
    }
}
